package com.wei.ssm.service.impl;

import com.wei.ssm.dao.IUserDao;
import com.wei.ssm.domain.Role;
import com.wei.ssm.domain.UserInfo;
import com.wei.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = null;

        try {
            userInfo = userDao.findByUserName(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = new User(userInfo.getUsername(),userInfo.getPassword(),userInfo.getStatus() == 0 ? false:true ,true,true,true,getAuthority(userInfo.getRoles()));
        return user;
    }

    public List<SimpleGrantedAuthority> getAuthority(List<Role> role){
        List<SimpleGrantedAuthority> list = new ArrayList<>();

        for (Role r:role
             ) {
            list.add(new SimpleGrantedAuthority("ROLE_"+r.getRoleName()));
        }
        return list;
    }

    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }

    @Override
    public void save(UserInfo user) {
        userDao.save(user);
    }

    @Override
    public UserInfo findById(int id) {
        return userDao.findById(id);
    }

    @Override
    public List<Role> findUserByIdAndAllRole(int id) {
        return userDao.findUserByIdAndAllRole(id);
    }

    @Override
    public void addRoleToUser(int userId, int[] ids) {

        //通过循环，逐步的添加
        for (int id:ids
             ) {
            userDao.addRoleToUser(userId,id);
        }

    }
}
